import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QCoreApplication
from PyQt5.QtWidgets import (QApplication, QWidget,
                             QPushButton, QProgressDialog, QVBoxLayout)


class DemoProgressDialog(QWidget):
    def __init__(self, parent=None):
        super(DemoProgressDialog, self).__init__(parent)

        # 设置窗口标题
        self.setWindowTitle('实战PyQt5: QProgressDialog Demo!')
        # 设置窗口大小
        self.resize(360, 120)

        self.initUi()

    def initUi(self):
        vLayout = QVBoxLayout(self)
        btnTest1 = QPushButton('进度对话框测试1', self)
        btnTest1.clicked.connect(self.onButtonTest1)
        btnTest2 = QPushButton('进度对话框测试2', self)
        btnTest2.clicked.connect(self.onButtonTest2)
        vLayout.addWidget(btnTest1)
        vLayout.addWidget(btnTest2)
        self.setLayout(vLayout)

    def onButtonTest1(self):
        elapsed = 50000
        dlg = QProgressDialog('进度', '取消', 0, elapsed, self)
        dlg.setWindowTitle('等待......')
        dlg.setWindowModality(Qt.WindowModal)
        dlg.show()
        for val in range(elapsed):
            dlg.setValue(val)
            QCoreApplication.processEvents()
            if dlg.wasCanceled():
                break
        dlg.setValue(elapsed)

    def onButtonTest2(self):
        pd = QProgressDialog('', '', 0, 1000, self)
        pd.setWindowTitle('等待......')
        pd.setLabelText('当前进度值')
        pd.setCancelButtonText('取消')
        pd.setRange(0, 1000)
        pd.setValue(500)
        # 1秒后弹出进度对话框
        pd.setMinimumDuration(0)
        pd.canceled.connect(lambda: print('进度对话框被取消'))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DemoProgressDialog()
    window.show()
    sys.exit(app.exec())
